<template>
  <div>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
    >
      <!-- @on-load="onLoad" -->

      <template slot="menuLeft">
        <el-button type="primary" size="small" @click.stop="addWhite">添加商户白名单</el-button>
        
      </template>

      <template slot="menu" slot-scope="{ row }">
        <el-button
          @click.stop="rowDel(row)"
          icon="el-icon-delete"
          type="text"
          size="small"
          >删 除</el-button
        >
      </template>

      <template slot-scope="{}" slot="serviceNoSearch">
        <select-page
          ref="searchSerSelect"
          label="serviceName"
          value="serviceNo"
          :select.sync="search.serviceNo"
          :url="website.searchLink.serviceUrl"
          placeholder-text="服务商"
          filter-key="searchParam"
        ></select-page>
      </template>

      <template slot-scope="{}" slot="rpiNoSearch">
        <select-page
          ref="searchRpiSelect"
          label="rpiName"
          value="rpiNo"
          :select.sync="search.rpiNo"
          :url="website.searchLink.merchantUrl"
          placeholder-text="商户"
          filter-key="searchParam"
        ></select-page>
      </template>

      <template slot-scope="{disabled,size}" slot="beginTimeSearch">
        <el-date-picker v-model="search.beginTime" type="datetime" value-format='yyyy-MM-dd HH:mm:ss' @change="beginTimeChange" placeholder="请输入创建开始日期"></el-date-picker>
      </template>

      <template slot-scope="{disabled,size}" slot="endTimeSearch">
        <el-date-picker v-model="search.endTime" type="datetime" default-time="23:59:59" value-format='yyyy-MM-dd HH:mm:ss' @change="endTimeChange" placeholder="请输入创建结束日期"></el-date-picker>
      </template>
    </avue-crud>

    <el-dialog
      :title="dialogModel.text"
      top="3%"
      :width="
        screenWidth > 1920
          ? '30%'
          : screenWidth <= 1920 && screenWidth > 1500
          ? '30%'
          : '90%'
      "
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogModel.visible"
      v-if="dialogModel.visible"
      :before-close="handleClose"
    >
      <div class="z_flex">
        <span style="min-width: 60px">商户:</span>
        <select-page
          ref="rpiFormSelect"
          style="width: 100% !important"
          label="rpiName"
          value="rpiNo"
          :select.sync="modelForm.rpiNo"
          :url="website.searchLink.merchantUrl"
          placeholder-text="商户"
          filter-key="searchParam"
        ></select-page>
      </div>
      <div slot="footer">
        <el-button size="small" type="primary" @click="modelSubmit">{{
          dialogModel.subText
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import selectPage from "@/components/select-page/select-page";
import { getMerchantList } from "@/api/rb-oem/optimizePolicies/deal";

export default {
  components: {
    selectPage,
  },
  props: {
    merhcantArr: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    const serviceTypeValidate = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入参数"));
      } else if (isNaN(value)) {
        callback(new Error("请输入数字型参数"));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!isMobile(value)) {
        callback(new Error("手机号码不正确！"));
      } else {
        callback();
      }
    };
    return {
      screenWidth: document.documentElement.clientWidth,
      loading: false,
      query: {},
      search: {},
      dialogVisible: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        selection: false,
        indexLabel: "序号",
        menuWidth: 100,
        searchMenuSpan: 24,
        searchLabelWidth: 120, //搜索框标题宽度
        // searchIcon:true,
        column: [
          {
            label: "服务商",
            prop: "serNo",
            type: "select",
            display: false,
            search: true,
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择服务商",
                trigger: "blur",
              },
            ],
            overHidden: true,
            minWidth: 150,
          },
          {
            label: "",
            prop: "isAllSer",
            type: "select",
            multiple: false,
            dataType: "string",
            showColumn: false,
            hide: true,
            search: true,
            searchType: "checkbox",
            searchSpan: 0,
            searchLabelWidth: "0",
            dicData: [
              {
                label: "包含下级",
                value: 1,
              },
            ],
          },
          {
            label: "商户编号",
            searchLabel: "商户",
            prop: "rpiNo",
            type: "select",
            minWidth: 140,
            display: false,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入商户号",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "门头名称",
            prop: "rpiName",
            type: "input",
            minWidth: 200,
            rules: [
              {
                required: true,
                message: "请输入门头名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "注册名称",
            prop: "registeredName",
            type: "input",
            minWidth: 200,
            rules: [
              {
                required: true,
                message: "请输入注册名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "商户简称",
            prop: "userShortName",
            type: "input",
            minWidth: 200,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入商户简称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "所属服务商",
            minWidth: 200,
            prop: "serName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "加入白名单时间",
            prop: "createTime",
            minWidth: 150,
            span: 24,
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: "创建开始日期",
            prop: "beginTime",
            search: true,
            hide: true,
            display: false,
          },
          {
            label: "创建结束日期",
            prop: "endTime",
            search: true,
            hide: true,
            display: false,
          },
        ],
      },
      dialogModel: {
        type: "",
        text: "",
        visible: false,
        subText: "",
      },
      checked: false,
      modelForm: {
        rpiNo:""
      },
      data: [],
      allData: [],
    };
  },
  watch: {
    merhcantArr: {
      handler(arr) {
        this.data = arr;
        if (arr.length > 0) {
          this.allData = arr;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  
  methods: {
    beginTimeChange() {
      if(this.search.endTime){
        if(Date.parse(this.search.beginTime) > Date.parse(this.search.endTime)){
          this.$alert('创建开始日期不能大于结束日期', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          .then(() => (this.search.beginTime = ""))
          .catch(() => (this.search.beginTime = ""))
        }
      }
    },
    endTimeChange() {
      if(this.search.beginTime){
        if(Date.parse(this.search.endTime) < Date.parse(this.search.beginTime)){
          this.$alert('创建结束日期不能小于开始日期', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          .then(() => (this.search.endTime = ""))
          .catch(() => (this.search.endTime = ""))
        }
      }
    },
    modelSubmit() {
      let that = this;
      console.log("---this.modelForm", this.dialogModel, this.modelForm);
      if (that.dialogModel.type == "add") {
        if (that.modelForm.rpiNo) {
          /**
           *  type 1.添加 2.删除 3.查询
           */
          let param = {
            ...that.modelForm,
            type: 1,
            merchantList: that.allData,
          };

          that.onLoad(param);
        } else {
          that.$message({
            type: "error",
            message: "请选择要添加白名单的商户！",
          });
        }
      } else {
        let param = {
          ...that.modelForm,
          type: 2,
          merchantList: that.allData,
        };
        that.onLoad(param);
      }
    },
    handleClose(done) {
      this.initDialogModel();
      done();
    },
    initDialogModel() {
      this.dialogModel = {
        type: "",
        text: "",
        visible: false,
        subText: "",
      };
      this.modelForm = {
        rpiNo: ""
      };
    },
    addWhite() {
      this.dialogModel = {
        type: "add",
        text: "添加白名单",
        visible: true,
        subText: "确认添加",
      };
    },
    delWhite() {
      this.dialogModel = {
        type: "del",
        text: "删除白名单",
        visible: true,
        subText: "确认删除",
      };
    },
    rowDel(row) {
      let that = this;
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let param = {
            type: 2,
            merchantList: that.allData,
            rpiNo: row.rpiNo,
          };

          return that.onLoad(param);
        })
        .then(() => {
          that.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    onLoad(params = {}) {
      let that = this;
      this.loading = true;
      /**
       * type: 1.添加 2.删除 3.查询
       */
      let param = {
        ...params,
      };

      if (JSON.stringify(params) == "{}") {
        param = {
          ...this.search,
          type: 3,
          merchantList: that.allData,
        };
      }

      getMerchantList(param).then((res) => {
        const data = res.data.data;
        this.data = data.merchantList;
        this.allData = data.allMerchantList;
        // this.page.total = data.total;
        this.loading = false;
        if (params.type === 1 || params.type === 2) {
          that.search = {};
        }
      });
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
    searchReset() {
      this.query = {};
      this.onLoad();
    },
    searchChange(params, done) {
      this.query = params;
      // this.page.currentPage = 1;
      this.onLoad();
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad();
    },
  },
};
</script>

<style lang="scss" scoped>
.z_flex {
  display: flex !important;
  align-items: center;
}

/deep/ .el-select--small {
  width: 100% !important;
}
</style>
